<?php

namespace App\Model\Admin;
use App\Model\BaseModel;

class Menu extends BaseModel
{
    protected $table = 'osc_admin_menu';

    function get_admin_menu($username,$group_id){

    	if($username==DbConfig('administrator')){
    		 $data = $this->db->where('type','nav')->where('status',1)->orderBy('sort_order','asc')->get($this->table);
    	}else{
    		$sql="select am.* from osc_admin_auth_rule as aar,osc_admin_menu as am where am.id=aar.menu_id and am.type='nav' and am.status=1 and aar.group_id=".$group_id." order by am.sort_order asc ";
    		$data=$this->db->rawQuery($sql);
    	}
        return empty($data) ? null : osc_tools('tree')->list_to_tree($data,'id','pid','children',0);
    }
	
	function get_all_menu(){
		$data = $this->db->orderBy('sort_order','asc')->get($this->table,null,'id,pid,title AS name,url');
        return empty($data) ? null : $data;
	}
	
	 function get_by_id($id){
        $data = $this->db->where('id',$id)->getOne($this->table);
        return empty($data) ? null : $data;
    }
	//取得当前元素的父节点
	 function get_by_pid($pid){
        $data = $this->db->where('pid',$pid)->getOne($this->table);
        return empty($data) ? null : $data;
    }
	
	function add($data){
	
		unset($data['id']);
		
		if($id= $this->db->insert($this->table,$data)){
			return $id;
		}else{
			return ['error'=>$this->db->getLastError()];
		}
	}
	function edit($data){
	
		$id=$data['id'];
		unset($data['id']);
		
		return $this->db->where('id',$id)->update($this->table,$data);
		
	}
	//删除单个元素
	 function delete($id){
        return $this->db->where('id',$id)->delete($this->table);
    }
	//删除所有子元素
	 function delete_all_childs($pid){
		 
		$menu=$this->get_all_menu();
		
		$childs=osc_tools('tree')->getChildsId($menu,$pid);
		
		foreach($childs as $k=>$v){
			$this->db->where('id',$v)->delete($this->table);
		}
		
		return true;
    }
	
	function get_auth_rule($ids,$prefix){		
		$table_name='osc_'.$prefix.'_auth_rule';
		
		//$data = $this->db->whereIn('menu_id',$ids)->get($table_name,null,'name');
		
		$sql="select name from ".$table_name." where menu_id in(".$ids.")";
		
		$data=$this->db->rawQuery($sql);

		return empty($data) ? null : $data;		
	}
	
	function get_auth_groups($uid,$prefix){

		$sql="select uid,group_id,title,rules from ".'osc_'.$prefix.'_auth_group_access as a left join '
		.'osc_'.$prefix.'_auth_group as g on a.group_id=g.id where a.uid='.$uid.' and g.status=1';
		
		$data=$this->db->rawQuery($sql);
		
		return empty($data) ? null : $data;	
	}
}